"""
爬取b站视频


1.获取B站视频网页源代码
2，解析数据，提取我们想要的标题/cid/session
3.把cid session 传入我们找到的playurl这个数据包里面
4.获取json字典数据
5.解析数据提供，音频url 视频url
6.保存数据
7.合成视频 把音频和视频内容合并在一起


三种查询方式，1.通过开发者工具media去查询，
            2.看数据包，搜索mp4,m4s,m4a ,m3u8
            3.一个个去查询，查看相应是否为乱码（二进制形式）
"""
import json
import os.path
import pprint
import re
import uuid

import tqdm
from bs4 import BeautifulSoup
import requests


def Splicing(t,title):
    os.system(f'ffmpeg -i "video/{t}.mp4" -i "video/{t}.mp3" -c -y copy "video/{title}.mp4 "')
    os.remove(f'video/{t}.mp4')
    os.remove(f'video/{t}.mp3')


def downloads_mp4(title, url, headers):
    res = requests.get(url, headers=headers)
    if not os.path.exists('video'):
        os.mkdir('video')
    with open(f'video/{title}.mp4', 'wb') as f:
        f.write(res.content)


def downloads_mp3(title, url, headers):
    res = requests.get(url, headers=headers)
    if not os.path.exists('video'):
        os.mkdir('video')
    with open(f'video/{title}.mp3', 'wb') as f:
        f.write(res.content)


headers = {
    # referer 防盗链
    "Referer": "https://www.bilibili.com/",
    "Cookie": "buvid3=B884A5B9-F9BC-1C62-3913-7097D067F15642970infoc; b_nut=1691250842; i-wanna-go-back=-1; _uuid=8A9365101-E8EF-B78B-32EE-7FE3A7108B26E51869infoc; buvid4=0CDC58EB-EF42-3452-E841-5D15CA4EA28444642-023080523-qS1NKbptMAuZqs3EsIfEVA%3D%3D; home_feed_column=4; header_theme_version=CLOSE; CURRENT_FNVAL=4048; rpdid=|(J|~u)|~YRk0J'uYmuJ)u)lJ; buvid_fp_plain=undefined; DedeUserID=353877534; DedeUserID__ckMd5=3f337514e9c8e6a5; CURRENT_QUALITY=80; b_ut=5; FEED_LIVE_VERSION=V8; nostalgia_conf=-1; hit-new-style-dyn=1; hit-dyn-v2=1; fingerprint=d9ee51905b59d2f1bccb48db1ef71db8; buvid_fp=d9ee51905b59d2f1bccb48db1ef71db8; SESSDATA=377be7e4%2C1708738025%2Cf2cde%2A81xvrMAcSz5sGbO4r-cGhRjocwV_BexkJ2aaqFE0XoDOi2btYueI28Lsqbb7SXPVff0pS-cgAAIgA; bili_jct=e6a899e3430193aad2e03f759da201df; bili_ticket=eyJhbGciOiJFUzM4NCIsImtpZCI6ImVjMDIiLCJ0eXAiOiJKV1QifQ.eyJleHAiOjE2OTM0NDUyMzQsImlhdCI6MTY5MzE4NjAzNCwicGx0IjotMX0.K5QXkpSDWirilCTEV7IFJYbEvnhzuGMdCWI99wqPSjuib0ApDMqsABbNYan4NLN3SHa3V4HzBR3L5Qia6HWsvLzGPEook0KsoJakFtu6qsgADc7dBWfxoxft9EJmkfed; bili_ticket_expires=1693445234; browser_resolution=1349-675; sid=5y5ri549; PVID=1; b_lsid=B28FBFF5_18A3A658085; bp_video_offset_353877534=834767331128246306",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.62",
}


def get_b_content(url, headers):
    with tqdm.tqdm(total=10) as f:
        # <h1 title="【2022最新】20个Python爬虫项目实战_一周练完，练完即就业！简历必备项目（附源码）" class="video-title" data-v-4f1c0915=""></h1>
        mp4_res = requests.get(url, headers=headers)
        if not mp4_res.status_code == 200:
            print(mp4_res.status_code)
            return
        title = re.findall('<title data-vue-meta="true">(.*?)</title>', mp4_res.text)

        soup = BeautifulSoup(mp4_res.text, 'html.parser')
        num = soup.find_all('span')
        play_info = re.findall(pattern='<script>window.__playinfo__=(.*?)</script>', string=mp4_res.text)[0]
        play_info = json.loads(play_info)
        t=uuid.uuid1()
        video_url = play_info['data']['dash']['video'][0]['base_url']
        audio_url = play_info['data']['dash']['audio'][0]['base_url']
        f.set_description(f"Downloading{title}")
        downloads_mp4(t, video_url, headers=headers)
        f.update(4)
        downloads_mp3(t, audio_url, headers=headers)
        f.update(4)
        Splicing(t,title)
        f.update(2)


if __name__ == "__main__":
    with tqdm.tqdm(total=197) as f:
        for i in range(1, 197):
            url = f"https://www.bilibili.com/video/BV1ZT4y1d7JM/?p={i}"
            get_b_content(url, headers)
        f.update(1)
